#include "Application/Application.h"
#include "Application/Window.h"
#include "LoginDlg.h"
#include "resource.h"
#include "Login/LoginManager.h"

INT_PTR CALLBACK GlobalDlgProc(
	HWND hwndDlg,
	UINT uMsg,
	WPARAM wParam,
	LPARAM lParam
	)
{
	return LoginManager::getSingletonPtr()->getDlg()->LoginDialogProc( hwndDlg, uMsg, wParam, lParam );
}


LoginDlg::LoginDlg()
{
}

LoginDlg::~LoginDlg()
{
	EndDialog(mhWnd, 0);
}

void LoginDlg::init()
{
	//set editbox to null
	//focus to name editbox
	mhName = GetDlgItem(mhWnd, IDC_EDIT_NAME);
	mhIP = GetDlgItem(mhWnd, IDC_EDIT_IP);
	mhPort = GetDlgItem(mhWnd, IDC_EDIT_PORT);
}

void LoginDlg::login(const char* name, const char* addr, int port)
{
	Network::getSingletonPtr()->connectServer(addr, port);
}

void LoginDlg::showDlg()
{
	if( 0 != DialogBox(Application::gethInstance(), MAKEINTRESOURCE(IDD_DLG_LOGIN), Window::getMainWindow()->getHWND(), GlobalDlgProc))
		assert(0&&"Dialog error");
}

INT_PTR LoginDlg::LoginDialogProc(
	HWND hwndDlg,
	UINT uMsg,
	WPARAM wParam,
	LPARAM lParam
	)
{
	switch(uMsg)
	{
	case WM_INITDIALOG:
		{
			mhWnd = hwndDlg;
			init();
		}
		break;
	case WM_COMMAND:
		{
			int wmID = LOWORD(wParam);
			int wmEvent = HIWORD(wParam);

			switch(wmID)
			{
			case IDC_BTN_LOGIN:
				{
					char name[64], IP[64], port[64];
					ZeroMemory(name, 64);
					ZeroMemory(IP, 64);
					ZeroMemory(port, 64);
					GetWindowText(mhName,	name,	64);
					GetWindowText(mhIP,		IP,		64);
					GetWindowText(mhPort,	port,	64);
					login(name, IP, atoi(port));
				}
				break;
			case IDC_BTN_QUIT:
				PostQuitMessage(0);
				break;
			}
		}
		break;
	}
	return 0;
}